package com.study.qqserve.service;

import com.study.qqcommon.Message;
import com.study.qqcommon.MessageType;
import com.study.qqserve.utils.Utility;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;

public class SendNewsToAllService implements Runnable {
    @Override
    public void run() {
        while (true){
            System.out.println("请输入要推送的新闻[输入exit退出推送服务 ]：");
            String news = Utility.readString(150);
            if("exit".equals(news)){
                break;
            }
            //构建消息对象
            Message message = new Message();
            message.setSender("服务器");
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setContent(news);
            message.setSendTime(new Date().toString());

            System.out.println("服务器推送给所有人的消息:" + news);
            //发送消息给所有在线用户

            HashMap<String, ServerContentThread> hm = MangerClientThreads.getAllServerContentThread();
            for (String onlineUserId : hm.keySet()) {
                try {
                    ObjectOutputStream oss = MangerClientThreads.getServerContentThread(onlineUserId).getObjectOutputStream();
                    oss.writeObject(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
